import axios from 'axios'
import qs from "qs";
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'

axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';


// create an axios instance
const service = axios.create({
  baseURL: "http://127.0.0.1:2333/", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么

    if (getToken() != null) {
      // 让每个请求携带令牌
      // ['token'] 是否为自定义标题键
      // 请根据实际情况进行修改
      config.headers['token'] = getToken()
    }

    //post进行封装
    if (config.method === 'post') {
      config.data = qs.stringify(config.data);
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * 如果您想要获取http信息，如header或状态
   * Please return  response => response
   */

  /**
   * 通过自定义代码确定请求状态
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 200, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      //
      if (res.code === 402) {
        // to re-login
        MessageBox.confirm('您已注销，请重新登录 ', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        })
        removeToken()
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
